<template>
  <div>
    <van-address-edit
      :area-list="areaList"
      show-postal
      show-delete
      show-set-default
      @change-area="changeArea"
      :address-info="addressInfo"
      @delete="delAddress"
      @save="onSave"
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
    />
  </div>
</template>

<script>
import areaList from '@/utils/area'
import { reqOneAddress, reqDelUserAddress, reqUpdUserAddress } from '@/api/user'
export default {
  data() {
    return {
      areaList,
      id: this.$route.params.id,
      addressInfo: {},
      areaCode: '',
    }
  },
  methods: {
    changeArea(areaArr) {
      // 拼接接口所需要的编号格式： 420000-420800-420881
      this.areaCode = areaArr.map((item) => item.code).join('-')
    },
    async onSave(address) {
      console.log(address, 'save')
      address.areaCode = this.areaCode

      let { status, message } = await reqUpdUserAddress(address)
      this.$toast(message)
      if (status === 0) {
        this.$router.back()
      }
    },
    async delAddress() {
      let { status, message } = await reqDelUserAddress(this.addressInfo.id)
      this.$toast(message)
      if (status === 0) {
        this.$router.back()
      }
    },
    async getAddressInfo() {
      const addressInfo = await reqOneAddress(this.id)
      console.log('ajax', addressInfo)
      this.areaCode = addressInfo.areaCode // 设置默认的areaCode
      addressInfo.areaCode = addressInfo.areaCode.split('-')[2] // 省市区编码，仅保留最后一个，即 areaCode: 360521

      // 回显地址信息
      this.addressInfo = addressInfo
    },
  },
  mounted() {
    // 获取当前用户地址
    this.getAddressInfo()
  },
}
</script>
